package com.cmic.rcs.emoji.interceptor;

import com.cmic.rcs.emoji.common.CustomContext;
import com.cmic.rcs.emoji.common.UserContext;
import com.cmic.rcs.emoji.entity.dto.UserDto;
import com.cmic.rcs.emoji.util.CommonUtils;
import com.cmic.rcs.enhance.message.g5.core.common.Response;
import com.cmic.rcs.enhance.message.g5.core.common.ResponseData;
import com.cmic.rcs.enhance.message.g5.core.common.ReturnCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;

import static com.cmic.rcs.emoji.common.CustomContext.TRACE_ID;

@Slf4j
@Component
public class SessionInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置traceId 作用是记录日志和追踪请求
        String traceId = StringUtils.defaultIfEmpty(request.getHeader(TRACE_ID), CommonUtils.getUuid());
        CustomContext.setTraceId(traceId);

        // 获取请求路径，排除不需要拦截的路径
        String requestURI = request.getRequestURI();
        log.info("SessionInterceptor拦截请求: {}", requestURI);

        // 排除验证码相关，登录的请求
        if (requestURI.contains("/captcha") || requestURI.contains("/login") ||
                requestURI.contains("/verify") || requestURI.contains("/refresh")) {
            log.info("SessionInterceptor不拦截请求: {}", requestURI);
            return true;
        }


        // 检查session中是否有登录信息
        Object adminAccount = request.getSession().getAttribute("adminAccount");
        Object adminName = request.getSession().getAttribute("adminName");

        if (adminAccount != null && adminName != null) {
            // 登录信息存在，设置用户上下文
            String userId = adminAccount.toString();
            String username = adminName.toString();
            UserContext.setUserDto(new UserDto(userId, username));
            log.info("Session验证通过，用户: {}", username);
            return true;
        } else {
            // 登录信息不存在，返回未登录状态
            log.info("Session验证失败，用户未登录");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            Response responseData = ResponseData.Error(ReturnCodeEnum.USER_NOT_LOGIN);
            out.write(objectMapper.writeValueAsString(responseData));
            out.flush();
            out.close();
            return false;
        }
    }

    // 处理请求后，返回结果前调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) {
        // Do nothing
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
        CustomContext.clear();
        UserContext.remove();
    }
}